
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff import stream

example_table_json = """
{
"atts": ["name", "age", "phone"],
"data": [
{"name": "aaron", "age":5, "phone": 1111},
{"name": "betty", "age":15, "phone": 2111},
{"name": "cathy", "age":25, "phone": 3111}
]
}
"""

class table(misc.utility):
    "format table from json representation"
    def __init__(self, variable="jsonData"):
        self.variable = variable
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        variable = self.param_value(self.variable, env)
        table_text = resolver.unquote(whiffenv.cgiGet(env, variable, example_table_json))
        table_json = self.param_json(table_text, env)
        atts = table_json["atts"]
        data = table_json["data"]
        highlight = table_json.get("highlight")
        L = ["<table border>"]
        L.append("<tr>")
        L.append("</tr>")
        for a in atts:
            L.append("<th>%s</th>" % a)
        for d in data:
            name = d["name"]
            if name==highlight:
                L.append('<tr bgcolor="yellow">')
            else:
                L.append('<tr bgcolor="cyan">')
            for a in atts:
                v = d[a]
                if a=="name":
                    L.append('<td> <a href="#" onclick="changeTable(\'%s\')">%s</td>' % (v,v))
                else:
                    L.append("<td>%s</td>" % v)
            L.append("</tr>")
        L.append("</table>")
        result = "\n".join(L)
        start_response("200 OK", [('Content-Type', "text/html")])
        #pr "result=", repr(result)
        return [stream.mystr(result)]

__middleware__ = table
    
